<template>
  <main>
    <h2 v-if="todos.length == 0">暂无待办事项</h2>
    <ul v-else>
      <li v-for="todo in todos" :key="todo.id">
        <input
          type="checkbox"
          :checked="todo.done"
          @change="handleToggleDone(todo.id)"
        />
        <span
          :class="todo.done ? 'done' : ''"
          v-if="!todo.edit"
          @click="handleToggleEdit(todo.id)"
          >{{ todo.content }}</span
        >
        <input
          type="text"
          v-else
          :value="todo.content"
          @blur="handleChangeContent($event, todo.id)"
          v-focus
        />
        <button @click="handleDel(todo.id)">删除</button>
      </li>
    </ul>
  </main>
</template>

<script setup>
const props = defineProps({
  todos: {
    type: Array,
    default: () => {
      return [];
    },
  },
});

const emits = defineEmits('toggleDone', 'toggleEdit', 'changeContent','del');
function handleToggleDone(id) {
  emits('toggleDone', id);
}
function handleToggleEdit(id) {
  emits('toggleEdit', id);
}
function handleChangeContent(e, id) {
  emits('changeContent', e, id);
}

// 使用自定义指令, 获取焦点
const vFocus = {
  mounted(el) {
    // 指令应用的DOM元素. 这里就是input元素
    el.focus()
  },
}

function handleDel(id) {
  emits('del',id);
}
</script>

<style scoped>
main h2 {
  text-align: center;
  margin-top: 10px;
}
main li {
  display: flex;
  align-items: center;
  height: 40px;
  padding: 0 40px;
  list-style: none;
  border-bottom: 1px solid #eee;
}
main li span {
  flex: 1;
  margin-left: 20px;
}
main li button {
  padding: 0 10px;
}

/* 代办事项删除的效果 */
ul li span.done {
  text-decoration: line-through;
  color: red;
}

/* 代办事项可编辑状态下的input样式 */
ul li input[type='text'] {
  flex: 1;
  margin-left: 20px;
  border: none;
  color: blue;
}
</style>
